#!/bin/bash

# Maxwell管理脚本
# 用于启动、停止、监控Maxwell服务

echo "=== Maxwell管理脚本 ==="
echo "时间: $(date)"
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
MAXWELL_HOME="/opt/module/maxwell"  # 请根据实际安装路径修改
MAXWELL_CONFIG="$MAXWELL_HOME/config.properties"
MAXWELL_LOG="$MAXWELL_HOME/logs/maxwell.log"
MAXWELL_PID="$MAXWELL_HOME/maxwell.pid"

# 检查Maxwell安装
check_maxwell_install() {
    if [ ! -d "$MAXWELL_HOME" ]; then
        echo -e "${RED}✗ Maxwell未安装或路径不正确: $MAXWELL_HOME${NC}"
        echo "请先安装Maxwell或修改MAXWELL_HOME变量"
        exit 1
    fi
    
    if [ ! -f "$MAXWELL_CONFIG" ]; then
        echo -e "${YELLOW}⚠ 配置文件不存在: $MAXWELL_CONFIG${NC}"
        echo "请先创建配置文件"
        exit 1
    fi
    
    echo -e "${GREEN}✓ Maxwell安装检查通过${NC}"
}

# 检查依赖服务
check_dependencies() {
    echo -e "${BLUE}检查依赖服务...${NC}"
    
    # 检查MySQL连接
    echo "检查MySQL连接..."
    if mysql -h 192.168.10.102 -P 3306 -u maxwell -pmaxwell -e "SELECT 1;" 2>/dev/null; then
        echo -e "${GREEN}✓ MySQL连接正常${NC}"
    else
        echo -e "${RED}✗ MySQL连接失败${NC}"
        return 1
    fi
    
    # 检查Kafka连接
    echo "检查Kafka连接..."
    if command -v kafka-topics.sh >/dev/null 2>&1; then
        if kafka-topics.sh --bootstrap-server hadoop102:9092 --list 2>/dev/null | grep -q "maxwell"; then
            echo -e "${GREEN}✓ Kafka连接正常，maxwell主题存在${NC}"
        else
            echo -e "${YELLOW}⚠ Kafka连接正常，但maxwell主题不存在${NC}"
            echo "创建maxwell主题..."
            kafka-topics.sh --bootstrap-server hadoop102:9092 --create --topic maxwell --partitions 3 --replication-factor 1 2>/dev/null
            if [ $? -eq 0 ]; then
                echo -e "${GREEN}✓ maxwell主题创建成功${NC}"
            else
                echo -e "${RED}✗ maxwell主题创建失败${NC}"
            fi
        fi
    else
        echo -e "${YELLOW}⚠ 未找到kafka-topics.sh，跳过Kafka检查${NC}"
    fi
}

# 启动Maxwell
start_maxwell() {
    echo -e "${BLUE}启动Maxwell...${NC}"
    
    check_maxwell_install
    check_dependencies
    
    # 检查是否已运行
    if [ -f "$MAXWELL_PID" ] && kill -0 $(cat "$MAXWELL_PID") 2>/dev/null; then
        echo -e "${YELLOW}⚠ Maxwell已在运行 (PID: $(cat $MAXWELL_PID))${NC}"
        return 0
    fi
    
    # 创建日志目录
    mkdir -p $(dirname "$MAXWELL_LOG")
    
    # 启动Maxwell
    echo "启动Maxwell进程..."
    nohup $MAXWELL_HOME/bin/maxwell --config="$MAXWELL_CONFIG" > "$MAXWELL_LOG" 2>&1 &
    MAXWELL_PROCESS_ID=$!
    
    # 保存PID
    echo $MAXWELL_PROCESS_ID > "$MAXWELL_PID"
    
    # 等待启动
    sleep 3
    
    # 检查启动状态
    if kill -0 $MAXWELL_PROCESS_ID 2>/dev/null; then
        echo -e "${GREEN}✓ Maxwell启动成功 (PID: $MAXWELL_PROCESS_ID)${NC}"
        echo "日志文件: $MAXWELL_LOG"
    else
        echo -e "${RED}✗ Maxwell启动失败${NC}"
        echo "请检查日志文件: $MAXWELL_LOG"
        rm -f "$MAXWELL_PID"
        return 1
    fi
}

# 停止Maxwell
stop_maxwell() {
    echo -e "${BLUE}停止Maxwell...${NC}"
    
    if [ -f "$MAXWELL_PID" ]; then
        PID=$(cat "$MAXWELL_PID")
        if kill -0 $PID 2>/dev/null; then
            echo "停止Maxwell进程 (PID: $PID)..."
            kill $PID
            
            # 等待进程结束
            for i in {1..10}; do
                if ! kill -0 $PID 2>/dev/null; then
                    echo -e "${GREEN}✓ Maxwell已停止${NC}"
                    rm -f "$MAXWELL_PID"
                    return 0
                fi
                sleep 1
            done
            
            # 强制杀死进程
            echo "强制停止Maxwell进程..."
            kill -9 $PID
            rm -f "$MAXWELL_PID"
            echo -e "${GREEN}✓ Maxwell已强制停止${NC}"
        else
            echo -e "${YELLOW}⚠ Maxwell进程不存在 (PID: $PID)${NC}"
            rm -f "$MAXWELL_PID"
        fi
    else
        echo -e "${YELLOW}⚠ 未找到PID文件${NC}"
        
        # 查找Maxwell进程
        PIDS=$(pgrep -f "maxwell")
        if [ -n "$PIDS" ]; then
            echo "找到Maxwell进程: $PIDS"
            echo "停止进程..."
            kill $PIDS
            sleep 2
            echo -e "${GREEN}✓ Maxwell已停止${NC}"
        else
            echo -e "${YELLOW}⚠ 未找到运行中的Maxwell进程${NC}"
        fi
    fi
}

# 重启Maxwell
restart_maxwell() {
    echo -e "${BLUE}重启Maxwell...${NC}"
    stop_maxwell
    sleep 2
    start_maxwell
}

# 检查Maxwell状态
status_maxwell() {
    echo -e "${BLUE}检查Maxwell状态...${NC}"
    
    if [ -f "$MAXWELL_PID" ]; then
        PID=$(cat "$MAXWELL_PID")
        if kill -0 $PID 2>/dev/null; then
            echo -e "${GREEN}✓ Maxwell正在运行 (PID: $PID)${NC}"
            
            # 显示进程信息
            echo "进程信息:"
            ps -p $PID -o pid,ppid,cmd,etime,pcpu,pmem
            
            # 显示连接信息
            echo "连接信息:"
            netstat -tlnp 2>/dev/null | grep $PID || echo "未找到网络连接"
            
            return 0
        else
            echo -e "${RED}✗ Maxwell进程不存在 (PID: $PID)${NC}"
            rm -f "$MAXWELL_PID"
            return 1
        fi
    else
        # 查找Maxwell进程
        PIDS=$(pgrep -f "maxwell")
        if [ -n "$PIDS" ]; then
            echo -e "${GREEN}✓ 找到Maxwell进程: $PIDS${NC}"
            return 0
        else
            echo -e "${RED}✗ Maxwell未运行${NC}"
            return 1
        fi
    fi
}

# 查看日志
show_logs() {
    echo -e "${BLUE}查看Maxwell日志...${NC}"
    
    if [ -f "$MAXWELL_LOG" ]; then
        echo "日志文件: $MAXWELL_LOG"
        echo "最后50行日志:"
        echo "----------------------------------------"
        tail -50 "$MAXWELL_LOG"
    else
        echo -e "${YELLOW}⚠ 日志文件不存在: $MAXWELL_LOG${NC}"
    fi
}

# 实时监控日志
monitor_logs() {
    echo -e "${BLUE}实时监控Maxwell日志...${NC}"
    
    if [ -f "$MAXWELL_LOG" ]; then
        echo "按 Ctrl+C 停止监控"
        echo "----------------------------------------"
        tail -f "$MAXWELL_LOG"
    else
        echo -e "${YELLOW}⚠ 日志文件不存在: $MAXWELL_LOG${NC}"
    fi
}

# 测试配置
test_config() {
    echo -e "${BLUE}测试Maxwell配置...${NC}"
    
    check_maxwell_install
    check_dependencies
    
    echo "测试Maxwell配置..."
    if $MAXWELL_HOME/bin/maxwell --config="$MAXWELL_CONFIG" --dry_run 2>/dev/null; then
        echo -e "${GREEN}✓ 配置测试通过${NC}"
    else
        echo -e "${RED}✗ 配置测试失败${NC}"
        echo "请检查配置文件: $MAXWELL_CONFIG"
    fi
}

# 显示帮助信息
show_help() {
    echo "使用方法: $0 {start|stop|restart|status|logs|monitor|test|help}"
    echo ""
    echo "命令说明:"
    echo "  start    - 启动Maxwell"
    echo "  stop     - 停止Maxwell"
    echo "  restart  - 重启Maxwell"
    echo "  status   - 检查Maxwell状态"
    echo "  logs     - 查看日志"
    echo "  monitor  - 实时监控日志"
    echo "  test     - 测试配置"
    echo "  help     - 显示帮助信息"
    echo ""
    echo "配置文件: $MAXWELL_CONFIG"
    echo "日志文件: $MAXWELL_LOG"
    echo "PID文件: $MAXWELL_PID"
}

# 主函数
main() {
    case "$1" in
        start)
            start_maxwell
            ;;
        stop)
            stop_maxwell
            ;;
        restart)
            restart_maxwell
            ;;
        status)
            status_maxwell
            ;;
        logs)
            show_logs
            ;;
        monitor)
            monitor_logs
            ;;
        test)
            test_config
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            echo -e "${RED}错误: 未知命令 '$1'${NC}"
            echo ""
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@" 